/**
 * Copyright (c) 2010 by Kevin Bierhoff.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *    1. Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *    3. Neither the names of the authors nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.syper.javasyp.checker;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.IVariableBinding;

import com.googlecode.syper.javasyp.formulae.Field;
import com.googlecode.syper.javasyp.formulae.Formula;
import com.googlecode.syper.javasyp.formulae.Local;
import com.googlecode.syper.javasyp.formulae.Name;
import com.googlecode.syper.javasyp.prover.SmtLib;

/**
 * @author kevin
 * @since Jun 4, 2010
 */
public class EasyLogicMethodVisitor extends AbstractLogicMethodVisitor<EasyHavocLookup> {

	@Override
	protected SmtLib createProver() {
		return new SmtLib(null, false);
	}

	@Override
	protected EasyHavocLookup createLookup(AST ast) {
		return new EasyHavocLookup(ast);
	}

	@Override
	protected Collection<Field> getFieldsIfName(Formula rhs) {
		try {
			// remember fields to equate, if any
			Name source = (Name) rhs;
			return getLookup().getKnownFields(source);
		} catch (ClassCastException e) {
			return Collections.emptyList();
		}
	}

	@Override
	protected void havocUnprotected(ASTNode node,
			Map<Name, ? extends Collection<IVariableBinding>> modifiable) {
		// THIS IS CRAZY INEFFICIENT
		// havoc fields of objects that are transitively
		// not protected by permissions.
		// this is necessary since we encode fields as regular variables
		// (may be able to avoid this altogether with map encoding a la Boogie)
		// the implementation used here breadth-first-searches fields reachable
		// transitively through permissions starting from locals.
		// optimization: only consider known fields (mentioned in formulae)
		// may be able to do this more efficiently if it was possible from
		// permission information in superclass to figure out which fields
		// are currently unprotected (instead of current Expression-based info).
		if (getLookup() == null)
			// outside methods
			return;
		Set<Name> checkFields = new LinkedHashSet<Name>();
		// TODO static methods?
		Local receiver = null;
		boolean receiverProtects = false;
		if (getReceiver() != null) {
			receiver = getLookup().getReceiver(getReceiver());
			receiverProtects = isReceiverProtects();
		}

		for (Map.Entry<IVariableBinding, PermKind> x :
			getLocalsAndReceiverFields().entrySet())
		{
			IVariableBinding o = x.getKey();
			if (o == null)
				// array.length
				continue;
			if (x.getValue() == null) {
				if (o.isField()) {
					if (receiver == null)
						// TODO static fields
						continue;
					if (receiverProtects)
						checkFields.add(getLookup().getField(receiver, o));
					else
						assume(getLookup().havoc(receiver,
								Collections.singleton(o)));
				} else if (!o.getType().isPrimitive()) {
					assume(getLookup()
							.havocKnownFields(getLookup().getLocal(o)));
				} // else primitive local, has no fields to havoc
			} else {
				// o is protected so we'll descend into its fields below
				checkFields.add(o.isField() ? getLookup().getField(receiver, o)
						: getLookup().getLocal(o));
			}
		}

		// seems like recursive part is pre-computable
		while (!checkFields.isEmpty()) {
			// breadth-first-search of fields until we hit unprotected ones
			Set<Name> newCheckFields = new LinkedHashSet<Name>();
			for (Name o : checkFields) {
				for (Field f : getLookup().getKnownFields(o)) {
					if (f.isArrayLength())
						continue;
					if (getChecker().getVariableType(f.getBinding()) == null)
						assume(getLookup().havocKnownFields(f));
					else
						newCheckFields.add(f);
				}
			}
			checkFields = newCheckFields;
		}
	}
}
